//
//  SLUserPermissionsManager.m
//  shunlianPower2
//
//  Created by 陈镇 on 2019/7/4.
//  Copyright © 2019 顺联网络. All rights reserved.
//

#import "SLUserPermissionsManager.h"
#import <AVFoundation/AVFoundation.h>
#import <EventKit/EventKit.h>
#import <UserNotifications/UserNotifications.h>
#import <CoreLocation/CoreLocation.h>
static NSString *pohotTip = @"未取得你的相册使用权限，此功能无法使用，请前往应用权限设置打开权限。";
static NSString *locationTip = @"未取得你的定位使用权限，此功能无法使用，请前往应用权限设置打开权限。";
static NSString *cameraTip = @"未取得你的相机使用权限，此功能无法使用，请前往应用权限设置打开权限。";
static NSString *adiuoTip = @"未取得你的麦克风使用权限，此功能无法使用，请前往应用权限设置打开权限。";

@implementation SLUserPermissionsManager





+(void)isHaveLocationAuthorizationBlock:(void (^)(BOOL))completionHandler{
    
    //未开全局定位
    if (![CLLocationManager locationServicesEnabled]) {
        
    
        completionHandler(NO);
        return;
    }
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            // 用户尚未做出选择
            completionHandler(YES);
            break;
        case kCLAuthorizationStatusRestricted:
            // 定位服务受限（可能是家长控制）
            completionHandler(NO);
            [SLUserPermissionsAlert showViewTitle:locationTip block:^(NSInteger index) {
            }];
            break;
        case kCLAuthorizationStatusDenied:
            // 用户明确拒绝或全局定位服务关闭
            [SLUserPermissionsAlert showViewTitle:locationTip block:^(NSInteger index) {
            }];
            completionHandler(NO);
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            // 拥有始终定位权限
            completionHandler(YES);
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            // 仅在使用应用时允许定位
            completionHandler(YES);
            break;
        default:
            break;
    }
}
+(void)isHavePhotoPermissionsBlock:(void (^)(BOOL))completionHandler{
    if ([QMUIAssetsManager authorizationStatus] == QMUIAssetAuthorizationStatusNotDetermined) {
        [QMUIAssetsManager requestAuthorization:^(QMUIAssetAuthorizationStatus status) {
            // requestAuthorization:(void(^)(QMUIAssetAuthorizationStatus status))handler 不在主线程执行，因此涉及 UI 相关的操作需要手工放置到主流程执行。
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status == QMUIAssetAuthorizationStatusAuthorized) {
                    if (completionHandler) {
                        completionHandler(YES);
                    }
                } else {
                    if (completionHandler) {
                        completionHandler(NO);
                    }
                    [SLUserPermissionsAlert showViewTitle:pohotTip block:^(NSInteger index) {
                    }];
                }
            });
        }];
    } else if ([QMUIAssetsManager authorizationStatus] == QMUIAssetAuthorizationStatusNotAuthorized) {
        if (completionHandler) {
            completionHandler(NO);
        }
        [SLUserPermissionsAlert showViewTitle:pohotTip block:^(NSInteger index) {
        }];
    } else {
        if (completionHandler) {
            completionHandler(YES);
        }
    }
}


+ (void)isHaveCameraPermissionsBlock:(void(^)(BOOL isCan))completionHandler
{
    [SLUserPermissionsManager isHaveCameraPermissionsTitle:nil block:completionHandler];
}
+ (void)isHaveCameraPermissionsTitle:(NSString *)title block:(void(^)(BOOL isCan))completionHandler {
    
    NSString *mediaType = AVMediaTypeVideo;     //读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];          //读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [SLUserPermissionsAlert showViewTitle:title.length==0?cameraTip:title block:^(NSInteger index) {
        }];
        // 提示语
        if (completionHandler) {
            completionHandler(NO);
        }
    }
    else if(authStatus == AVAuthorizationStatusNotDetermined) { //第一次请求。
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completionHandler) {
                    if (granted) {
                        completionHandler(granted);
                    }else{
                        [SLUserPermissionsAlert showViewTitle:title.length==0?cameraTip:title block:^(NSInteger index) {
                        }];
                    }
                    
                }
            });
        }];
        
    }else {
        if (completionHandler) {
            completionHandler(YES);
        }
    }
    
}
+(void)isHaveAudioPermissionsBlock:(void(^)(BOOL isCan))completionHandler{
    [SLUserPermissionsManager isHaveAudioPermissionsTitle:nil block:completionHandler];
}
+ (void)isHaveAudioPermissionsTitle:(NSString *)title block:(void(^)(BOOL isCan))completionHandler {
    
    AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    AVAudioSession *avSession = [AVAudioSession sharedInstance];
    //判断是否询问过用户授权麦克风（否则检测麦克风权限，会被APP询问授权弹窗打断）
    if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
        [SLUserPermissionsAlert showViewTitle:title.length==0?adiuoTip:title block:^(NSInteger index) {
        }];
        // 提示语
        if (completionHandler) {
            completionHandler(NO);
        }
    }else if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {
        if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
            
            [avSession requestRecordPermission:^(BOOL available) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (available) {
                        if (completionHandler) {
                            completionHandler(YES);
                        }
                    }else {
                        if (completionHandler) {
                            completionHandler(NO);
                            [SLUserPermissionsAlert showViewTitle:title.length==0?adiuoTip:title block:^(NSInteger index) {
                            }];
                        }
                    }
                    
                });
                
            }];
        }
    }else {
        if (completionHandler) {
            completionHandler(YES);
        }
    }
    
}
+(void)isHaveCameraAndAudioPermissionsBlock:(void (^)(BOOL))completionHandler{
    NSString *title = @"麦克风、相机权限未开启，此功能无法使用，请前往应用权限设置打开权限。";
    [SLUserPermissionsManager isHaveCameraPermissionsTitle:title block:^(BOOL isCan) {
        if (isCan) {
            [SLUserPermissionsManager isHaveAudioPermissionsTitle:title block:^(BOOL isCan) {
                if (completionHandler) {
                    completionHandler(isCan);
                }
            }];
        }
    }];
    
    
}

//判断有没有日历权限
+(void)isHaveCalendarPermissionsBlock:(void(^)(BOOL isCan))completionHandler{
    NSString *title = @"日历权限未开启，此功能无法使用，请前往应用权限设置打开权限。";
    
    EKAuthorizationStatus EKstatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    
    if (EKstatus == EKAuthorizationStatusNotDetermined) {
        if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
            [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error){
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (!granted){
                        if (completionHandler) {
                            completionHandler(YES);
                        }
                    }else{
                        if (completionHandler) {
                            completionHandler(NO);
                        }
                        [SLUserPermissionsAlert showViewTitle:title block:^(NSInteger index) {}];
                    }
                });
            }];
        }
    }else if (EKstatus == EKAuthorizationStatusAuthorized){
        if (completionHandler) {
            completionHandler(YES);
        }
    }else{
        if (completionHandler) {
            completionHandler(NO);
        }
        [SLUserPermissionsAlert showViewTitle:title block:^(NSInteger index) {
        }];
    }
    
    
}

//判断有没有开启通知
+ (void)isHaveNotificationPermissionsBlock:(void(^)(BOOL isCan))completionHandler {
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                    if (completionHandler) {
                        completionHandler(NO);
                    }
                }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                    if (completionHandler) {
                        completionHandler(NO);
                    }
                }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                    if (completionHandler) {
                        completionHandler(YES);
                    }
                }
            });
        }];
    }else {
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        if (setting.types == UIUserNotificationTypeNone) {
            //用户未开启APP的通知
            if (completionHandler) {
                completionHandler(NO);
            }
    //            NSString *title = @"推送权限未开启，此功能无法使用，请前往应用权限设置打开权限。";
    //            [SLUserPermissionsAlert showViewTitle:title block:^(NSInteger index) {}];
        }else{
            if (completionHandler) {
                completionHandler(YES);
            }
        }
    }
}

+ (void)isDeterminedNotificationPermissionsBlock:(void (^)(BOOL))completionHandler {
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                if (completionHandler) {
                    completionHandler(NO);
                }
            }else {
                if (completionHandler) {
                    completionHandler(YES);
                }
            }
        }];
    }else {
        if (completionHandler) {
            completionHandler(YES);
        }
    }
}

@end



@implementation SLUserPermissionsAlert

+(void)showViewTitle:(NSString *)title block:(void (^)(NSInteger index))block{
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"权限提示" message:title preferredStyle:UIAlertControllerStyleAlert];
                                
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }];
        
    [alert addAction:cancel];
    
    UIAlertAction *go = [UIAlertAction actionWithTitle:@"去启动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SLUserPermissionsAlert gotoUserNotificationSetting];
    }];
    [alert addAction:go];
    
    [CurrentVC presentViewController:alert animated:YES completion:nil];
    
    

}
+(void)gotoUserNotificationSetting{
    
    NSURL *url= [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if( [[UIApplication sharedApplication]canOpenURL:url] ) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication]openURL:url options:@{}completionHandler:^(BOOL success) {
            }];
        } else {
            [[UIApplication sharedApplication]openURL:url];
        }
    }
    
}
@end
